import 'dart:math';
import 'dart:ui' as ui;

import 'package:flame/events.dart' as events;
import 'package:flame/extensions.dart';
import 'package:flame/game.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_shader/widgets/shadertoy.dart';
import 'package:flutter_shader/widgets/transparent_navigation_bar.dart';

/// Created by changlei on 2024/2/23.
///
/// game页面
class GameScaffold extends StatelessWidget {
  /// game页面
  const GameScaffold({
    super.key,
    required this.assetKey,
    required this.builder,
  });

  /// assetKey
  final String assetKey;

  /// builder
  final FlameGame Function(ui.FragmentShader shader) builder;

  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
      navigationBar: const TransparentNavigationBar(),
      child: SizedBox.expand(
        child: ShaderBuilder(
          assetKey: assetKey,
          builder: (context, shader, child) {
            if (shader == null) {
              child = const Center(
                child: CupertinoActivityIndicator(
                  radius: 24,
                ),
              );
            } else {
              child = GameWidget(
                game: builder(shader),
              );
            }
            return child;
          },
        ),
      ),
    );
  }
}

/// game
abstract class ShaderGame extends FlameGame with events.DragCallbacks {
  /// game
  ShaderGame(this.shader) : paint = Paint()..shader = shader;

  /// shader
  final ui.FragmentShader shader;

  /// paint
  final ui.Paint paint;

  @override
  void render(ui.Canvas canvas) {
    super.render(canvas);
    canvas.save();
    canvas
      ..translate(size.x, size.y)
      ..rotate(pi)
      ..drawRect(
        Vector2.zero() & size,
        paint,
      );
    canvas.restore();
  }
}
